package demo;

/**
 * <p>
 * volatile 使用测试
 * </P>
 *
 * @author dingwen
 * @date 2021.10.14 17:37
 */
public class VolatileTest extends Thread {

    /**
     * 不加 volatile 修饰，线程会在自己的工作线程中获取值。没有感知到main线程修改了变量。故无法停止该线程
     */
    volatile boolean flag = true;
    int i = 0;

    @Override
    public void run() {
        while (flag) {
            i++;
        }

    }

    public static void main(String[] args) throws Exception {
        VolatileTest volatileTest = new VolatileTest();
        volatileTest.start();
        Thread.sleep(2000);
        volatileTest.flag = false;
        System.out.println(volatileTest.i);
    }
}
